package service

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"sync"
	"time"
)

const (
	translateUrl    = "https://open.feishu.cn/open-apis/translation/v1/text/translate"
	accessTokenUrl  = "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal"
	appID           = "cli_a649beee2f29900b"             // 需要替换为实际的app_id
	appSecret       = "cJmcWcF334FT4ZwpyGIgKfLGGknmjx0F" // 需要替换为实际的app_secret
	tokenExpireTime = 10 * time.Hour                     // 令牌过期时间，飞书默认是2小时，这里设置为10小时
)

// getFeishuLanguageCode 获取飞书支持的语言代码
func getFeishuLanguageCode(langCode string) string {
	// 直接映射常用语言代码，避免复杂的map定义
	switch langCode {
	case "zh":
		return "zh_CN" // 中文简体
	case "en":
		return "en" // 英语
	case "ja":
		return "ja" // 日语
	case "ko":
		return "ko" // 韩语
	case "fr":
		return "fr" // 法语
	case "de":
		return "de" // 德语
	case "es":
		return "es" // 西班牙语
	case "ru":
		return "ru" // 俄语
	case "pt":
		return "pt" // 葡萄牙语
	case "it":
		return "it" // 意大利语
	case "ar_sa":
		return "ar" // 阿拉伯语
	default:
		return "en" // 默认使用英语
	}
}

// FeishuService 飞书服务
type FeishuService struct {
	tenantAccessToken string
	tokenExpireAt     time.Time
	mutex             sync.Mutex
}

var feishuService *FeishuService
var onceFeishuService sync.Once

// GetFeishuService 获取飞书服务实例
func GetFeishuService() *FeishuService {
	onceFeishuService.Do(func() {
		feishuService = &FeishuService{}
	})
	return feishuService
}

// TenantAccessTokenResponse 租户访问令牌响应
type TenantAccessTokenResponse struct {
	Code              int    `json:"code"`
	Msg               string `json:"msg"`
	TenantAccessToken string `json:"tenant_access_token"`
	Expire            int    `json:"expire"`
}

// TranslateRequest 翻译请求
type TranslateRequest struct {
	SourceLanguage string `json:"source_language"`
	TargetLanguage string `json:"target_language"`
	Text           string `json:"text"`
}

// TranslateResponse 翻译响应
type TranslateResponse struct {
	Code int          `json:"code"`
	Msg  string       `json:"msg"`
	Data TranslateData `json:"data"`
}

// TranslateData 翻译数据
type TranslateData struct {
	Text string `json:"text"`
}

// getTenantAccessToken 获取租户访问令牌
func (s *FeishuService) getTenantAccessToken() (string, error) {
	s.mutex.Lock()
	defer s.mutex.Unlock()

	// 检查令牌是否有效
	if s.tenantAccessToken != "" && time.Now().Before(s.tokenExpireAt) {
		return s.tenantAccessToken, nil
	}

	// 构建请求体
	reqBody := map[string]string{
		"app_id":     appID,
		"app_secret": appSecret,
	}

	reqBytes, err := json.Marshal(reqBody)
	if err != nil {
		return "", err
	}

	// 发送请求
	resp, err := http.Post(accessTokenUrl, "application/json", bytes.NewBuffer(reqBytes))
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	// 解析响应
	respBody, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}

	var tokenResp TenantAccessTokenResponse
	if err := json.Unmarshal(respBody, &tokenResp); err != nil {
		return "", err
	}

	if tokenResp.Code != 0 {
		return "", fmt.Errorf("get tenant access token failed: %s", tokenResp.Msg)
	}

	// 更新令牌和过期时间
	s.tenantAccessToken = tokenResp.TenantAccessToken
	s.tokenExpireAt = time.Now().Add(tokenExpireTime)

	return s.tenantAccessToken, nil
}

// Translate 调用飞书翻译接口
func (s *FeishuService) Translate(sourceLang, targetLang, text string) (string, error) {
	// 获取访问令牌
	token, err := s.getTenantAccessToken()
	if err != nil {
		return "", err
	}

	// 映射语言代码到飞书支持的语言代码
	feishuSourceLang := getFeishuLanguageCode(sourceLang)
	feishuTargetLang := getFeishuLanguageCode(targetLang)

	log.Printf("Translating from %s to %s: %s\n", feishuSourceLang, feishuTargetLang, text)

	// 构建请求体
	req := TranslateRequest{
		SourceLanguage: feishuSourceLang,
		TargetLanguage: feishuTargetLang,
		Text:           text,
	}

	reqBytes, err := json.Marshal(req)
	if err != nil {
		return "", err
	}

	// 创建请求
	httpReq, err := http.NewRequest("POST", translateUrl, bytes.NewBuffer(reqBytes))
	if err != nil {
		return "", err
	}

	// 设置请求头
	httpReq.Header.Set("Content-Type", "application/json")
	httpReq.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))

	// 发送请求
	client := &http.Client{}
	resp, err := client.Do(httpReq)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	// 解析响应
	respBody, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}

	log.Printf("Feishu API response: %s\n", string(respBody))

	var translateResp TranslateResponse
	if err := json.Unmarshal(respBody, &translateResp); err != nil {
		return "", err
	}

	if translateResp.Code != 0 {
		return "", fmt.Errorf("translate failed: %s", translateResp.Msg)
	}

	return translateResp.Data.Text, nil
}
